import 'dart:convert';
import 'dart:typed_data';

import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:flutter_quill_extensions/flutter_quill_extensions.dart';
import 'package:get/get.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:fate_blind_box/network/http_request.dart';

import 'package:dio/dio.dart' as dioFile;
import '../../../../theme/theme_color.dart';

class ActEditorPage extends StatefulWidget {
  Function? savAction;
  String jsonStr = '';

  ActEditorPage({this.savAction, this.jsonStr = '', Key? key})
      : super(key: key);

  @override
  State<ActEditorPage> createState() => _ActEditorPageState();
}

class _ActEditorPageState extends State<ActEditorPage> {
  late QuillController editController;

  FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      title: '活动详细描述',
      childWidget: QuillProvider(
        configurations: QuillConfigurations(
          controller: editController,
          sharedConfigurations: const QuillSharedConfigurations(),
        ),
        child: Column(
          children: [
            Expanded(
              child: QuillEditor.basic(
                configurations: QuillEditorConfigurations(
                  placeholder: '请输入活动详情描述',
                  readOnly: false,
                  autoFocus: false,
                  enableSelectionToolbar: true,
                  expands: false,
                  padding: EdgeInsets.zero,
                  onImagePaste: _onImagePaste,
                  customStyles: const DefaultStyles(
                    h1: DefaultTextBlockStyle(
                        TextStyle(
                          fontSize: 32,
                          color: Colors.black,
                          height: 1.15,
                          fontWeight: FontWeight.w300,
                        ),
                        VerticalSpacing(16, 0),
                        VerticalSpacing(0, 0),
                        null),
                    sizeSmall: TextStyle(fontSize: 9),
                  ),
                  embedBuilders: [
                    ...FlutterQuillEmbeds.builders(),
                  ],
                ),
              ),
            ),
            QuillToolbar(
              configurations: QuillToolbarConfigurations(
                embedButtons: FlutterQuillEmbeds.buttons(
                  onImagePickCallback: _onImagePickCallback,
                ),
                buttonOptions: QuillToolbarButtonOptions(
                  base: QuillToolbarBaseButtonOptions(
                    afterButtonPressed: focusNode.requestFocus,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      rightActions: [
        UnconstrainedBox(
          child: CupertinoButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              subMitAddressInfo();
            },
            child: Container(
              margin: const EdgeInsets.only(right: 15),
              width: 54,
              height: 31,
              decoration: BoxDecoration(
                color: ThemeColor.appColor,
                borderRadius: BorderRadius.circular(5),
              ),
              alignment: Alignment.center,
              child: const Text(
                '保存',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ),
        ),
      ],
    );
  }

  //保存输入的内容
  subMitAddressInfo() {
    var jsonStr = jsonEncode(editController.document.toDelta().toJson());
    if (widget.savAction != null) {
      widget.savAction!(jsonStr);
    }
    Get.back();
  }

  Future<String> _onImagePaste(Uint8List imageBytes) async {
    // Saves the image to applications directory
    final appDocDir = await getApplicationDocumentsDirectory();
    final file = await File(
      '${appDocDir.path}/${path.basename('${DateTime.now().millisecondsSinceEpoch}.png')}',
    ).writeAsBytes(imageBytes, flush: true);
    return file.path.toString();
  }

  Future<String> _onImagePickCallback(File file) async {
    // Copies the picked file from temporary cache to applications directory
    final appDocDir = await getApplicationDocumentsDirectory();
    final copiedFile =
        await file.copy('${appDocDir.path}/${path.basename(file.path)}');

    var res = await HttpRequest.uploadFile('member/activity/queryActiUrl',
        params: {
          'fileUrl': dioFile.MultipartFile.fromFileSync(copiedFile.path)
        });
    String imgUrl = copiedFile.path;
    if (res['code'] == 0) {
      imgUrl = res['data'];
    }
    return imgUrl;
  }

  @override
  void initState() {
    super.initState();
    if (widget.jsonStr.isNotEmpty) {
      var myJSON = jsonDecode(widget.jsonStr);
      editController = QuillController(
        document: Document.fromJson(myJSON),
        selection: TextSelection.collapsed(offset: 0),
      );
    } else {
      editController = QuillController.basic();
    }
  }
}
